package com.lanxin.kh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.kh.entity.KhProduct;
import com.lanxin.kh.service.IKhProductService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 产品前端控制器（仅接收参数并传递给Service）
 * </p>
 *
 * @author zyq
 * @since 2025-07-23
 */
@Controller
@RequestMapping("/kh/product")
public class KhProductController {

    private static final Logger logger = Logger.getLogger(KhProductController.class);

    @Autowired
    private IKhProductService khProductService;

    /**
     * 产品列表页
     */
    @RequestMapping("/listKhProduct")
    public String listKhProduct(Model model,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "5") Integer pageSize,
                                HttpServletRequest request) {
        // 获取搜索参数
        String linkname = request.getParameter("linkname");

        // 构建分页和查询条件
        Page<KhProduct> pageParam = new Page<>(page, pageSize);
        QueryWrapper<KhProduct> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(linkname)) {
            queryWrapper.like("linkname", linkname);
        }
        queryWrapper.orderByDesc("oid");

        // 调用Service查询
        IPage<KhProduct> pageInfo = khProductService.page(pageParam, queryWrapper);

        // 传递数据到页面
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("searchLinkname", linkname);
        return "kh/listKhProduct";
    }

    /**
     * 删除产品
     */
    @RequestMapping("/deleteKhProduct")
    @ResponseBody
    public boolean deleteKhProduct(@RequestParam("oid") Integer oid) {
        if (oid == null) {
            logger.error("删除产品失败：oid为空");
            return false;
        }
        boolean result = khProductService.removeById(oid);
        logger.info("删除产品结果：" + (result ? "成功" : "失败") + "，oid=" + oid);
        return result;
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping("/toAddKhProduct")
    public String toAddKhProduct(Model model) {
        return "kh/AddKhProduct";
    }

    /**
     * 添加产品（接收参数并传递给Service）
     */
    @RequestMapping("/addKhProduct")
    public String addKhProduct(KhProduct khProduct,
                               @RequestParam("imgfile") MultipartFile imgfile,
                               Model model,
                               HttpServletRequest request) {
        try {
            // 调用Service处理添加逻辑
            boolean result = khProductService.addProduct(khProduct, imgfile, request);
            if (result) {
                logger.info("添加产品成功：" + khProduct.getLinkname());
            } else {
                logger.error("添加产品失败：" + khProduct.getLinkname());
                model.addAttribute("errorMsg", "添加失败，请重试");
                return "kh/AddKhProduct";
            }
        } catch (Exception e) {
            logger.error("添加产品异常", e);
            model.addAttribute("errorMsg", "添加失败：" + e.getMessage());
            return "kh/AddKhProduct";
        }
        return "redirect:/kh/product/listKhProduct";
    }

    /**
     * 跳转到编辑页面
     */
    @RequestMapping("/toUpdateKhProduct")
    public String toUpdateKhProduct(Model model, @RequestParam Integer oid) {
        KhProduct khProduct = khProductService.getById(oid);
        model.addAttribute("khProduct", khProduct);
        return "kh/UpdateKhProduct";
    }

    /**
     * 更新产品（接收参数并传递给Service）
     */
    @RequestMapping("/updateKhProduct")
    public String updateKhProduct(KhProduct khProduct,
                                  @RequestParam(value = "imgfile", required = false) MultipartFile imgfile,
                                  Model model,
                                  HttpServletRequest request) {
        try {
            // 调用Service处理更新逻辑
            boolean result = khProductService.updateProduct(khProduct, imgfile, request);
            if (result) {
                logger.info("更新产品成功：" + khProduct.getOid());
            } else {
                logger.error("更新产品失败：" + khProduct.getOid());
                model.addAttribute("errorMsg", "更新失败，请重试");
                return "kh/UpdateKhProduct";
            }
        } catch (Exception e) {
            logger.error("更新产品异常", e);
            model.addAttribute("errorMsg", "更新失败：" + e.getMessage());
            return "kh/UpdateKhProduct";
        }
        return "redirect:/kh/product/listKhProduct";
    }

    /**
     * 校验产品名称是否存在
     */
    @RequestMapping("/checkKhProductName")
    @ResponseBody
    public Map<String, Boolean> checkKhProductName(
            @RequestParam("name") String name,
            @RequestParam(value = "oid", required = false) Integer oid) {
        Map<String, Boolean> result = new HashMap<>();
        // 调用Service校验
        boolean exists = khProductService.checkNameExists(name, oid);
        result.put("valid", !exists); // valid为true表示可用
        return result;
    }
}